package com.mn.sso.starter.config;



import cn.hutool.core.util.StrUtil;
import com.smart.sso.client.SmartContainer;
import com.smart.sso.client.filter.LoginFilter;
import com.smart.sso.client.filter.LogoutFilter;
import com.smart.sso.client.listener.LogoutListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author liutao
 * @date 2022年01月14日 19:00
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(SsoProperties.class)
public class SsoConfig {

    @Resource
    private SsoProperties ssoProperties;

    /**
     * 单点登录Filter容器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<SmartContainer> smartContainer() {
        log.info("ssoProperties:{}", ssoProperties);
        SmartContainer smartContainer = new SmartContainer();
        smartContainer.setServerUrl(ssoProperties.getServer().getUrl());
        smartContainer.setAppId(ssoProperties.getApp().getId());
        smartContainer.setAppSecret(ssoProperties.getApp().getSecret());

        if (StrUtil.isNotBlank(ssoProperties.getExcludeUrls())) {
            // 忽略拦截URL,多个逗号分隔
            smartContainer.setExcludeUrls(ssoProperties.getExcludeUrls());
        }

        smartContainer.setFilters(new LogoutFilter(), new LoginFilter());

        FilterRegistrationBean<SmartContainer> registration = new FilterRegistrationBean<>();
        registration.setFilter(smartContainer);
        registration.addUrlPatterns(ssoProperties.getFilter().getUrls());
        registration.setOrder(ssoProperties.getFilter().getOrder());
        registration.setName(ssoProperties.getRegisterName());
        return registration;
    }
}
